#include <unistd.h>
#include <vector>  
#include <cmath> 
#include "track.cpp"
#include "../include/common.hpp"
#include "../include/uart.hpp"
#include "../include/detection.hpp"  //百度Paddle框架移动端部署

int main() 
{
/**************配置文件读取***************/
  if(usefilehave()==1)
  {
    cerr << "Error opening file" << endl; 
    return 1;
  }
/**************显示窗口初始化***************/
  if(showimg==1)display_window_init();
/**************初始化类***************/
  imageprocess track;       //基础赛道处理类
  VideoCapture capture;     // Opencv相机类
/**************USB转串口初始化： /dev/ttyUSB0***************/
  shared_ptr<Uart> uart = make_shared<Uart>("/dev/ttyUSB0"); // 初始化串口驱动
  int uret = uart->open();
  if (uret != 0) {
    cerr << "Error opening Uart" << endl;  
    return -1;  }
/***************摄像头初始化*******************************/
  if(camera==1)capture = VideoCapture("/dev/video0"); // 打开摄像头
  else capture = VideoCapture("../car/sample.mp4"); // 打开摄像头
    if (!capture.isOpened()) {
      cerr << "Error opening capture" << endl;  
      return 0;}
/*****************图像分辨率修改****************************/
  capture.set(CAP_PROP_FRAME_WIDTH, COLSIMAGE);  // 设置图像分辨率
  capture.set(CAP_PROP_FRAME_HEIGHT, ROWSIMAGE); // 设置图像分辨率
/********************AI模型初始化***************************/
  shared_ptr<Detection> detection = make_shared<Detection>("../model/yolov3_mobilenet_v1");    
  Mat frame;
  Mat imageGray, roi_img,denoisendimage;
  int imgnum = 0;
  while (1) 
  { 
    speed = commonspeed;
    capture >> frame;                           //获取摄像头图象值
    detection->inference(frame);                //开始推理
    detection->drawBox(frame);                   //为AI元素画框
    
    cvtColor(frame, imageGray, COLOR_BGR2GRAY);     //图像灰度化
    GaussianBlur(imageGray,denoisendimage,Size(5,5),0);//图像高斯滤波
    threshold(denoisendimage, roi_img, 0, 255, THRESH_OTSU);//二值化
    track.Detectionline(roi_img);//识别赛道

   /***********************蜂鸣器线程控制******************/
   if(buzzer)
   {
    imgnum++;
    if(imgnum>=buzzernum)
    {
      imgnum=0;
      buzzer=false;
    }
   }
  /***********************中线拟合******************/
      track.servo();//计算舵机值
      if(showimg == 1){
      track.drawimg(rgb_window_name,frame);}//显示
      uart->sendpwm(speed,track.dutypwm,buzzer);
      if(saveimg==1)savePicture(frame);   //存图
        // 按'q'键退出循环
        char c = (char)waitKey(1);
        if (c == 'q' || c == 27) 
        {
          uart->sendpwm(0,1500,buzzer);
          uart->sendpwm(0,1500,buzzer);
          break;
        }
    } 
    return 0;  
}
